<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
class SalesOrder extends Model
{

    // 表名
    protected $name = 'kuyou_goods_sales_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->page($page,$limit)->field("id,purchase_code,purchase_type,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,sales_order_id,number,all_money,status,preparation_id,examine_id,check_status,examine_status,note,print_num")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->field("id,purchase_code,purchase_type,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,sales_order_id,number,all_money,status,preparation_id,examine_id,check_status,examine_status,note,print_num")->select())->toArray();
        }

        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['customers'] = (new Customers())->where(['id'=>$list_v['customers_id']])->value('customer_name');
            $list[$list_k]['preparation_name'] = (new User())->where(['id'=>$list_v['preparation_id']])->value('username');
            $list[$list_k]['examine_name'] = (new User())->where(['id'=>$list_v['examine_id']])->value('username');
            unset($list[$list_k]['preparation_id']);
            unset($list[$list_k]['examine_id']);

            $purchase_id = Db::name('kuyou_goods_saleord')->where(['order_id'=>$list_v['id']])->column('purchase_id');
            $purchase = Db::name('kuyou_goods_sales')->where(['id'=>['in',$purchase_id]])->column('purchase_code');
            $list[$list_k]['sales_order_id'] = implode(',',$purchase);
        }
        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param string $purchase_code
     * @return array
     */
    public static function getDetail($purchase_code){
        $detail = self::where(function ($query) use ($purchase_code) {
            $query->where('purchase_code', '=', $purchase_code);
        })->field("id,purchase_code,purchase_type,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,sale_user,FROM_UNIXTIME(delivery_time,'%Y-%m-%d') as delivery_time,note,preferential_rate,preferential_money,real_money,receiving_address,examine_status")->find();
        if($detail){
            $detail['customers'] = (new Customers())->where(['id'=>$detail['customers_id']])->value('customer_name');
            $detail['sales_name'] = (new StaffMember())->where(['id'=>$detail['sale_user']])->value('name');
            $where = [];
            $where['purchase_code'] = $detail['purchase_code'];
            $list = Db::name('kuyou_goods_sales_order_info')->alias('po')
                ->join('kuyou_goods g','g.goods_code=po.goods_code')
                ->join('kuyou_unit u','u.id=po.goods_unit')
                ->join('kuyou_stores s','s.id=po.stores_id')
                ->where($where)
                ->field("po.id,po.purchase_code,po.purchase_type,FROM_UNIXTIME(po.purchase_time,'%Y-%m-%d') as purchase_time,
            po.goods_code,g.goods_name,g.goods_image,po.goods_note,po.goods_attr,po.goods_unit,u.name as unit_name,po.stores_id,s.name as stores_name,po.allow_stock,po.number,po.default_unit,
            po.basic_nmber,po.unit_price,po.tax_included,po.discount,po.dis_money,po.all_money,po.tax_rate,po.tax_money,po.money_tax_price,po.remark")->select();
            foreach ($list as $list_k=>$list_v){
                $list[$list_k]['default_unit_name'] = (new Unit())->where(['id'=>$list_v['default_unit']])->value('name');
                
                $list[$list_k]['attr_name'] = '';
                if(!empty($list_v['goods_attr'])){
                    $attribute_id = Db::name('kuyou_goods_attr')->where(['id'=>$list_v['goods_attr']])->value('attribute_id');
                    $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$attribute_id])->value('attr_ids');
                    if($attribute_ids){
                        $attribute_ids = explode('&',$attribute_ids);
                        $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                        $list[$list_k]['attr_name'] = implode('/',$attribute);
                    }
                }
            }
            $detail['info_list'] = $list;
            //查询原始单据
            $enclosure_id = Db::name('kuyou_enclosure_log')->where(['order_id'=>$detail['id'],'type'=>'4'])->column('enclosure_id');
            if(!empty($enclosure_id)){
                $detail['enclosure_count'] = sizeof($enclosure_id);
                $detail['enclosure_ids'] = implode(',',$enclosure_id);
                $detail['enclosure_data'] = Db::name('kuyou_enclosure')->where(['id'=>['in',$enclosure_id]])->field('id,image')->select();
            }else{
                $detail['enclosure_count'] = 0;
                $detail['enclosure_ids'] = '';
                $detail['enclosure_data'] = [];
            }
        }
        if(!empty($detail)){
            return ['status'=>200,'msg'=>$detail];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号'=>'require',
                'purchase_type|单据类型'=>'require|in:1,2',
                'purchase_time|单据时间'=>'require',
                'delivery_time|交货时间'=>'require',
                'customers_id|客户'=>'require',
                'real_money|优惠后金额'=>'require',
                'info_list|详细购货信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],10);//验证编号是否合法
                if($status){
                    $examine= (new Commons())->getSet('examine','is_checked');
                    $detail['info_list'] = (array)json_decode($detail['info_list'], true);

                    $detail['sale_user'] = isset($detail['sale_user'])?$detail['sale_user']:null;
                    $detail['receiving_address'] = isset($detail['receiving_address'])?$detail['receiving_address']:'';

                    $customers = Db::name('kuyou_customers')->where(['id'=>$detail['customers_id']])->find();
                    if(empty($customers)){
                        return ['status'=>500,'msg'=>'客户不存在'];
                    }

                    $data = [];
                    $number = 0;$all_money = 0;$tax_money=0;$money_tax_price=0;
                    foreach ($detail['info_list'] as $k=>$v){
                        if(!empty($v['goods_code'])){//有产品编号
                            $number+=(float)$v['number'];
                            $all_money+=(float)$v['all_money'];
                            $tax_money += (float)$v['tax_money'];
                            $money_tax_price += (float)$v['money_tax_price'];
                            if(!isset($v['stores_id']) || empty($v['stores_id'])){
                                return ['status'=>500,'msg'=>'请选择仓库'];
                            }

                            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->find();
                            if(empty($goods)){
                                return ['status'=>500,'msg'=>'商品不存在'];
                            }elseif ($goods['auxiliary']==1 && empty($v['goods_attr'])){
                                return ['status'=>500,'msg'=>'请选择商品属性'];
                            }

                            $data[] = [
                                'purchase_code'     =>  $detail['purchase_code'],
                                'purchase_type'     =>  $detail['purchase_type'],
                                'purchase_time'     =>  strtotime($detail['purchase_time']),
                                'delivery_time'     =>  strtotime($detail['delivery_time']),
                                'customers_id'      =>  (int)$detail['customers_id'],//客户
                                'sale_user'         =>  (int)$detail['sale_user'],//销售员
                                'receiving_address' =>  $detail['receiving_address'],

                                'goods_code'        =>  $v['goods_code'],//商品信息
                                'goods_note'        =>  $v['goods_note'],
                                'goods_unit'        =>  (int)$v['goods_unit'],

                                'stores_id'         =>  (int)$v['stores_id'],
                                'allow_stock'       =>  (float)$v['allow_stock'],
                                'number'            =>  (float)$v['number'],
                                'purchase_number'   =>  (float)$v['number'],
                                'default_unit'      =>  (float)$v['default_unit'],
                                'basic_nmber'       =>  (float)$v['basic_nmber'],
                                'unit_price'        =>  (float)$v['unit_price'],
                                'discount'          =>  (float)$v['discount'],
                                'dis_money'         =>  (float)$v['dis_money'],
                                'all_money'         =>  (float)$v['all_money'],
                                'remark'            =>  $v['remark'],

                                'preferential_rate' =>  (float)$detail['preferential_rate'],
                                'preferential_money'=>  (float)$detail['preferential_money'],
                                'real_money'        =>  (float)$detail['real_money'],

                                'goods_attr'        =>  (float)$v['goods_attr'],
                                'tax_included'      =>  (float)$v['tax_included'],
                                'tax_rate'          =>  (float)$v['tax_rate'],
                                'tax_money'         =>  (float)$v['tax_money'],
                                'money_tax_price'   =>  (float)$v['money_tax_price'],

                                'preparation_id'    =>  $adminId,
                                'operation_id'      =>  $adminId,

                                'library_number'    =>  (float)$v['number'],
                                'library_money'     =>  (float)$v['all_money'],

                                'createtime'        => time(),
                                'updatetime'        => time(),
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_type'     =>  $detail['purchase_type'],
                            'purchase_time'     =>  strtotime($detail['purchase_time']),
                            'delivery_time'     =>  strtotime($detail['delivery_time']),
                            'customers_id'      =>  (int)$detail['customers_id'],//客户
                            'sale_user'         =>  (int)$detail['sale_user'],//销售员
                            'receiving_address' =>  $detail['receiving_address'],
                            'number'            =>  $number,
                            'all_money'         =>  $all_money,

                            'tax_money'         =>  $tax_money,
                            'money_tax_price'   =>  $money_tax_price,

                            'preferential_rate' =>  (float)$detail['preferential_rate'],
                            'preferential_money'=>  (float)$detail['preferential_money'],
                            'real_money'        =>  (float)$detail['real_money'],
                            'note'              =>  $detail['note'],
                            'preparation_id'    =>  $adminId,
                            'operation_id'      =>  $adminId,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }

                    $model = new SalesOrder();
                    $row = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                    }

                    //附件记录开始
                    $enclosureLog = [];
                    if(isset($detail['enclosure']) && !empty($detail['enclosure'])){//选择了原始单据
                        if(!empty($detail['enclosure'])){
                            $enclosure = explode(',',$detail['enclosure']);
                            $enclosurelist = Db::name('kuyou_enclosure')->where(['id'=>['in',$detail['enclosure']]])->select();
                            if(sizeof($enclosurelist)!=sizeof($enclosure)){
                                return ['status'=>500,'msg'=>'选择的原始单据有误，请重新选择'];
                            }else{
                                foreach ($enclosure as $k=>$v){
                                    $enclosureLog[] = [
                                        'enclosure_id'  => $v,
                                        'purchase_code' => $detail['purchase_code'],
                                        'type'          => '4',
                                    ];
                                }
                            }
                        }
                        unset($detail['enclosure']);
                    }
                    //附件记录结束

                    $result = false;
                    Db::startTrans();
                    try {
                        $model->allowField(true)->save($rowdata);
                        $result = $model->id;

                        //添加附件记录
                        if(!empty($enclosureLog)){
                            foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                                $enclosureLog[$enclosureLog_k]['order_id'] = $result;
                            }
                            Db::name('kuyou_enclosure_log')->insertAll($enclosureLog);
                        }
                        //添加附件记录结束

                        (new SalesOrderInfo())->allowField(true)->saveAll($data);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        if($examine!=1){
                            try {
                                $exa = self::examine($detail['purchase_code']);
                            } catch (Exception $e) {
                            }
                            if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                try {
                                    self::delDetail($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                return ['status'=>500,'msg'=>$exa['msg']];
                            }
                        }
                        return ['status'=>200,'msg'=>$detail['purchase_code']];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'old_purchase_code|原单据编号'=>'require',
                'purchase_code|单据编号'=>'require',
                'purchase_type|单据类型'=>'require|in:1,2',
                'purchase_time|单据时间'=>'require',
                'delivery_time|交货时间'=>'require',
                'customers_id|客户'=>'require',
                'real_money|优惠后金额'=>'require',
                'info_list|详细购货信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],10);//验证编号是否合法
                if($status){
                    $examine= (new Commons())->getSet('examine','is_checked');

                    $model = new SalesOrder();
                    $row = $model->where(['purchase_code'=>$detail['old_purchase_code']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'修改的单据不存在'];
                    }

                    if($row['examine_status']==1 && $examine==1){
                        return ['status'=>500,'msg'=>'不能编辑已审核的购货订单'];
                    }
                    if($row['purchase_type']==1){
                        $purchase_id = Db::name('kuyou_goods_saleord')->where(['order_id'=>$row['id']])->column('purchase_id');
                        if(!empty($purchase_id)){
                            return ['status'=>500,'msg'=>'不能编辑已生成购货单的数据'];
                        }
                    }else{
                        $purchase_id = Db::name('kuyou_goods_saleexc')->where(['purchase_id'=>$row['id']])->column('exchange_id');
                        if(!empty($purchase_id)){
                            return ['status'=>500,'msg'=>'不能编辑已生成退货单的数据'];
                        }
                    }

                    $detail['info_list'] = (array)json_decode($detail['info_list'], true);

                    $data = [];
                    $number = 0;$all_money = 0;$tax_money=0;$money_tax_price=0;
                    foreach ($detail['info_list'] as $k=>$v){
                        if(!empty($v['goods_code'])){//有产品编号
                            $number+=(float)$v['number'];
                            $all_money+=(float)$v['all_money'];
                            $tax_money += (float)$v['tax_money'];
                            $money_tax_price += (float)$v['money_tax_price'];
                            if(!isset($v['stores_id']) || empty($v['stores_id'])){
                                return ['status'=>500,'msg'=>'请选择仓库'];
                            }

                            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->find();
                            if(empty($goods)){
                                return ['status'=>500,'msg'=>'商品不存在'];
                            }elseif ($goods['auxiliary']==1 && empty($v['goods_attr'])){
                                return ['status'=>500,'msg'=>'请选择商品属性'];
                            }

                            $data[] = [
                                'purchase_code'     =>  $detail['purchase_code'],
                                'purchase_type'     =>  $detail['purchase_type'],
                                'purchase_time'     =>  strtotime($detail['purchase_time']),
                                'delivery_time'     =>  strtotime($detail['delivery_time']),
                                'customers_id'      =>  (int)$detail['customers_id'],//客户
                                'sale_user'         =>  (int)$detail['sale_user'],//销售员
                                'receiving_address' =>  $detail['receiving_address'],

                                'goods_code'        =>  $v['goods_code'],//商品信息
                                'goods_note'        =>  $v['goods_note'],
                                'goods_unit'        =>  (int)$v['goods_unit'],

                                'stores_id'         =>  (int)$v['stores_id'],
                                'allow_stock'       =>  (float)$v['allow_stock'],
                                'number'            =>  (float)$v['number'],
                                'purchase_number'   =>  (float)$v['number'],
                                'default_unit'      =>  (float)$v['default_unit'],
                                'basic_nmber'       =>  (float)$v['basic_nmber'],
                                'unit_price'        =>  (float)$v['unit_price'],
                                'discount'          =>  (float)$v['discount'],
                                'dis_money'         =>  (float)$v['dis_money'],
                                'all_money'         =>  (float)$v['all_money'],
                                'remark'            =>  $v['remark'],

                                'preferential_rate' =>  (float)$detail['preferential_rate'],
                                'preferential_money'=>  (float)$detail['preferential_money'],
                                'real_money'        =>  (float)$detail['real_money'],

                                'goods_attr'        =>  (float)$v['goods_attr'],
                                'tax_included'      =>  (float)$v['tax_included'],
                                'tax_rate'          =>  (float)$v['tax_rate'],
                                'tax_money'         =>  (float)$v['tax_money'],
                                'money_tax_price'   =>  (float)$v['money_tax_price'],

                                'preparation_id'    =>  $adminId,
                                'operation_id'      =>  $adminId,

                                'library_number'    =>  (float)$v['number'],
                                'library_money'     =>  (float)$v['all_money'],

                                'createtime'        => time(),
                                'updatetime'        => time(),
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_type'     =>  $detail['purchase_type'],
                            'purchase_time'     =>  strtotime($detail['purchase_time']),
                            'delivery_time'     =>  strtotime($detail['delivery_time']),
                            'customers_id'      =>  (int)$detail['customers_id'],//客户
                            'sale_user'         =>  (int)$detail['sale_user'],//销售员
                            'receiving_address' =>  $detail['receiving_address'],
                            'number'            =>  $number,
                            'all_money'         =>  $all_money,

                            'tax_money'         =>  $tax_money,
                            'money_tax_price'   =>  $money_tax_price,

                            'preferential_rate' =>  (float)$detail['preferential_rate'],
                            'preferential_money'=>  (float)$detail['preferential_money'],
                            'real_money'        =>  (float)$detail['real_money'],
                            'note'              =>  $detail['note'],
                            'preparation_id'    =>  $adminId,
                            'operation_id'      =>  $adminId,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }

                    if($detail['purchase_code']!=$detail['old_purchase_code']){
                        $purchase_id = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                        if($purchase_id){
                            return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                        }
                    }

                    //附件记录开始
                    $enclosureLog = [];
                    if(isset($detail['enclosure']) && !empty($detail['enclosure'])){//选择了原始单据
                        if(!empty($detail['enclosure'])){
                            $enclosure = explode(',',$detail['enclosure']);
                            $enclosurelist = Db::name('kuyou_enclosure')->where(['id'=>['in',$detail['enclosure']]])->select();
                            if(sizeof($enclosurelist)!=sizeof($enclosure)){
                                return ['status'=>500,'msg'=>'选择的原始单据有误，请重新选择'];
                            }else{
                                foreach ($enclosure as $k=>$v){
                                    $enclosureLog[] = [
                                        'enclosure_id'  => $v,
                                        'purchase_code' => $detail['purchase_code'],
                                        'type'          => '4',
                                    ];
                                }
                            }
                        }
                        unset($detail['enclosure']);
                    }
                    //附件记录结束

                    if($row){
                        $res = false;
                        Db::startTrans();
                        try {
                            //关闭审核功能需先反审核一次已审核数据
                            if($examine!=1 && $row['examine_status']==1){
                                self::examinef($detail['old_purchase_code']);
                            }
                            //添加附件记录
                            Db::name('kuyou_enclosure_log')->where(['order_id'=>$row['id'],'type'=>'4'])->delete();
                            if(!empty($enclosureLog)){
                                foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                                    $enclosureLog[$enclosureLog_k]['order_id'] = $row['id'];
                                }
                                Db::name('kuyou_enclosure_log')->insertAll($enclosureLog);
                            }
                            //添加附件记录结束
                            $rowdata['updatetime'] = time();
                            $res = $model->where(['purchase_code'=>$detail['old_purchase_code']])->update($rowdata);
                            (new SalesOrderInfo)->where(['purchase_code'=>$detail['old_purchase_code']])->delete();
                            (new SalesOrderInfo)->allowField(true)->saveAll($data);
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            if($examine!=1){
                                try {
                                    $exa = self::examine($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                    return ['status'=>500,'msg'=>$exa['msg']];
                                }
                            }
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param string $purchase_code
     * @return array
     */
    public static function delDetail($purchase_code){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $purchase_code = explode(',',$purchase_code);
            $model = new SalesOrder();
            $examine= (new Commons())->getSet('examine','is_checked');

            $list = $model->where(['purchase_code'=>['in',$purchase_code]])->select();
            foreach ($list as $list_k=>$list_v){
                if($list_v['examine_status']==1 && $examine==1){
                    return ['status'=>500,'msg'=>'不能删除已审核的数据'];
                }
            }
            foreach ($list as $list_k=>$list_v){
                if($list_v['purchase_type']==1){
                    $purchase_id = Db::name('kuyou_goods_saleord')->where(['order_id'=>$list_v['id']])->column('purchase_id');
                    if(!empty($purchase_id)){
                        return ['status'=>500,'msg'=>'不能删除已生成购货单的数据'];
                    }
                }else{
                    $purchase_id = Db::name('kuyou_goods_saleexc')->where(['purchase_id'=>$list_v['id'],'type'=>'1'])->column('exchange_id');
                    if(!empty($purchase_id)){
                        return ['status'=>500,'msg'=>'不能删除已生成退货单的数据'];
                    }
                }
            }

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['examine_status']==1 && $examine!=1){
                        try {
                            self::examinef($v['purchase_code']);
                        } catch (Exception $e) {
                        }
                    }
                    $res = $model->where(['purchase_code'=>$v['purchase_code']])->delete();
                    $count += $res;
                    (new SalesOrderInfo)->where(['purchase_code'=>$v['purchase_code']])->delete();
                    //删除附件记录
                    Db::name('kuyou_enclosure_log')->where(['order_id'=>$v['id'],'type'=>'4'])->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$res];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 审核
     * @param array $purchase_code
     * @return array
     */
    public static function examine($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>500,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $model = new SalesOrder();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要审核的数据'];
        }
        Db::startTrans();
        try {
            $result = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
            Db::name('kuyou_goods_sales_order_info')->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->update(['examine_status'=>'1','examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'审核失败'];
        }
    }

    /**
     * 反审核
     * @param array $purchase_code
     * @return array
     */
    public static function examinef($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>500,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $model = new SalesOrder();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->field('id,purchase_id,purchase_type')->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要反审核的数据'];
        }
        foreach ($list as $list_k=>$list_v){
            if($list_v['purchase_type']==1){
                $purchase_id = Db::name('kuyou_goods_saleord')->where(['order_id'=>$list_v['id']])->column('purchase_id');
                if(!empty($purchase_id)){
                    return ['status'=>500,'msg'=>'不能反审核已生成销货单的数据'];
                }
            }else{
                $purchase_id = Db::name('kuyou_goods_saleexc')->where(['purchase_id'=>$list_v['id'],'type'=>'1'])->column('exchange_id');
                if(!empty($purchase_id)){
                    return ['status'=>500,'msg'=>'不能反审核已生成退货单的数据'];
                }
            }
        }
        Db::startTrans();
        try {
            $result = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->update(['examine_status'=>0,'examine_id'=>0,'examine_time'=>'','operation_id'=>$adminId]);
            Db::name('kuyou_goods_sales_order_info')->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->update(['examine_status'=>'0','examine_id'=>0,'examine_time'=>'','operation_id'=>$adminId]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'反审核失败'];
        }
    }

    /**
     * 检测是否可生成购货单
     * @param string $purchase_code
     * @return array
     */
    public static function checkPurchase($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>500,'msg'=>'请选择要操作的数据'];
        }
        $model = new SalesOrder();
        $row = $model->where(['purchase_code'=>$purchase_code])
            ->field('examine_status,purchase_code,purchase_type')
            ->find();
        if(empty($row)){
            return ['status'=>500,'msg'=>'未找到相关数据'];
        }
        $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
        if($examine==1){
            if($row['examine_status']!=1){
                return ['status'=>500,'msg'=>'此销货订单未审核'];
            }
        }
        $purchase_info = Db::name('kuyou_goods_sales_order_info')->where(['purchase_code'=>$row['purchase_code']])->select();
        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
            if($row['purchase_type']==1){
                $purord_info = Db::name('kuyou_goods_saleord_info')->where(['order_id'=>$purchase_info_v['id']])->field('sum(number) as number,sum(money) as money')->select();
                $gp_number = isset($purord_info[0]['number'])?$purord_info[0]['number']:0;
                if($purchase_info_v['number']-$gp_number<=0){
                    unset($purchase_info[$purchase_info_k]);
                }
            }else{
                $purord_info = Db::name('kuyou_goods_saleexc_info')->where(['purchase_id'=>$purchase_info_v['id'],'type'=>'1'])->field('sum(number) as number,sum(money) as money')->select();
                $gp_number = isset($purord_info[0]['number'])?$purord_info[0]['number']:0;
                if($purchase_info_v['number']-$gp_number<=0){
                    unset($purchase_info[$purchase_info_k]);
                }
            }
        }
        if(empty($purchase_info)){
            if($row['purchase_type']==1){
                return ['status'=>500,'msg'=>'此销货订单已全部生成销货单'];
            }else{
                return ['status'=>500,'msg'=>'此销货订单已全部生成退货单'];
            }
        }
        return ['status'=>200,'msg'=>''];
    }
}
